package com.songlanyun.modules.express.model;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import com.songlanyun.common.config.resttplconfig.RestUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

@Component
public class JiSuKDUtil {
    //极速快递appKey
    @Value("${jisukuaidi.appkey}")
    private String AppKey;

    //请求url
    @Value("${jisukuaidi.requrl}")
    private String ReqURL;

    @Resource
    private RestUtil restUtil;

    /**
     * Json方式 查询订单物流轨迹  -- 传入手机号
     *
     * @throws Exception
     */
    public KDInfo getOrderTracesByJsonByMobile(String expNo, String mobile) throws Exception {
        Map<String, Object> params = new HashMap<>();
        params.put("appkey", AppKey);
        params.put("type", "auto");//快递公司 自动识别请写auto
        params.put("number", expNo);//快递单号
        params.put("mobile", mobile);//收件人/寄件人手机号（顺丰快递需要）

        Map kdRes = restUtil.getForEntity(ReqURL, Map.class, params);
        //查询成功
        if (MapUtil.getInt(kdRes, "status") == 0) {
            //返回结果
            Map result = (Map) kdRes.get("result");

            KDInfo kdInfo = new KDInfo();
            kdInfo.setLogisticCode(MapUtil.getStr(result, "number"));//快递单号
            kdInfo.setShipperCode(MapUtil.getStr(result, "type"));//快递公司

            Integer deliverystatus = MapUtil.getInt(result, "deliverystatus");//物流状态 1在途中 2派件中 3已签收 4派送失败(拒签等)
            String state = "";
            switch (deliverystatus) {
                case 1:
                    state = "2";
                    break;
                case 2:
                    state = "2";
                    break;
                case 3:
                    state = "3";
                    break;
                default:
                    state = "4";
            }
            kdInfo.setState(state);
            kdInfo.setSuccess(true);

            List<KDTraces> traces = new ArrayList<>();
            List<Map<String, Object>> list = (List<Map<String, Object>>) result.get("list");
            if (CollectionUtil.isNotEmpty(list)) {
                list.forEach(l -> {
                    KDTraces kdTraces = new KDTraces();
                    kdTraces.setAcceptStation(MapUtil.getStr(l, "status"));
                    kdTraces.setAcceptTime(MapUtil.getStr(l, "time"));
                    traces.add(kdTraces);
                });

                traces.sort(Comparator.comparing(KDTraces::getAcceptTime));
            }
            kdInfo.setTraces(traces);
            //转换成kdInfo
            return kdInfo;
        }


        return null;
    }

}
